﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WeShare.WeiXin.Common;
using WeShare.WeiXin.Common.EnumKey;
using WeShare.WeiXin.Mp.Oauth.Entity;
#if !NET40
using System.Threading.Tasks;
#endif
namespace WeShare.WeiXin.Mp.Oauth
{
    public class OauthApi
    {
        /// <summary>
        /// 获取授权的url，默认使用snsapi_base方式
        /// </summary>
        /// <param name="redirectUri">授权后重定向的回调链接地址，方法内已进行url编码，调用时，无需再次编码</param>
        /// <param name="state">重定向后会带上state参数，开发者可以填写a-zA-Z0-9的参数值，最多128字节</param>
        /// <param name="authType">应用授权作用域</param>
        /// <param name="appid">公众号的唯一标识</param>
        /// <returns></returns>
        public static string GetAuthUrl(string redirectUri, string state, AuthType authType = AuthType.snsapi_base,string appid="")
        {
            var config = OpenApi.GetConfig(appid,PlatformType.Mp);
            var url =
            "https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope={2}&state={3}#wechat_redirect";
            return string.Format(url, config.AppId, HttpUtility.UrlEncode(redirectUri), authType, state);
        }
        /// <summary>
        /// 检查AuthToken是否有效
        /// </summary>
        /// <param name="authToken"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static BaseRes CheckAuthToken(string authToken, string openid)
        {
            var url =
                $"https://api.weixin.qq.com/sns/auth?access_token={authToken}&openid={openid}";
            return HttpUtil.GetResult<BaseRes>(url);
        }
        /// <summary>
        /// 刷新网页授权access_token.
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public static OAuthToken GetRefreshToken(string refreshToken,string appid="")
        {
            var config = OpenApi.GetConfig(appid,PlatformType.Mp);
            var url =
                $"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={appid}&grant_type=refresh_token&refresh_token={refreshToken}";
            return HttpUtil.GetResult<OAuthToken>(url);
        }

        /// <summary>
        /// 网页授权获取用户信息，仅网页授权作用域为snsapi_userinfo时有效
        /// </summary>
        /// <param name="authToken"></param>
        /// <param name="openid"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static UserInfo GetUserInfo(string authToken, string openid, string lang = "zh_CN")
        {
            var url =
                $"https://api.weixin.qq.com/sns/userinfo?access_token={authToken}&openid={openid}&lang={lang}";
            return HttpUtil.GetResult<UserInfo>(url);
        }
        /// <summary>
        /// 通过code换取网页授权access_token
        /// </summary>
        /// <param name="appid">公众号的唯一标识</param>
        /// <param name="code">填写第一步获取的code参数</param>
        /// <returns></returns>
        public static OAuthToken GetAuthToken(string code,string appid="")
        {
            var config = OpenApi.GetConfig(appid,PlatformType.Mp);
            var url =
                $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={config.AppId}&secret={config.AppSecret}&code={code}&grant_type=authorization_code";
            return HttpUtil.GetResult<OAuthToken>(url);
        }


#if !NET40
        /// <summary>
        /// 检查AuthToken是否有效
        /// </summary>
        /// <param name="authToken"></param>
        /// <param name="openid"></param>
        /// <returns></returns>
        public static async Task<BaseRes> CheckAuthTokenAsync(string authToken, string openid)
        {
            var url = $"https://api.weixin.qq.com/sns/auth?access_token={authToken}&openid={openid}";
            return await HttpUtil.GetResultAsync<BaseRes>(url);
        }
        /// <summary>
        /// 刷新网页授权access_token.
        /// </summary>
        /// <param name="appid"></param>
        /// <param name="refreshToken"></param>
        /// <returns></returns>
        public static async Task<OAuthToken> GetRefreshTokenAsync(string refreshToken, string appid = "")
        {
            var config = OpenApi.GetConfig(appid, PlatformType.Mp);
            var url = $"https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={appid}&grant_type=refresh_token&refresh_token={refreshToken}";
            return await HttpUtil.GetResultAsync<OAuthToken>(url);
        }

        /// <summary>
        /// 网页授权获取用户信息，仅网页授权作用域为snsapi_userinfo时有效
        /// </summary>
        /// <param name="authToken"></param>
        /// <param name="openid"></param>
        /// <param name="lang"></param>
        /// <returns></returns>
        public static async Task<UserInfo> GetUserInfoAsync(string authToken, string openid, string lang = "zh_CN")
        {
            var url = $"https://api.weixin.qq.com/sns/userinfo?access_token={authToken}&openid={openid}&lang={lang}";
            return await HttpUtil.GetResultAsync<UserInfo>(url);
        }
        /// <summary>
        /// 通过code换取网页授权access_token
        /// </summary>
        /// <param name="appid">公众号的唯一标识</param>
        /// <param name="code">填写第一步获取的code参数</param>
        /// <returns></returns>
        public static async Task<OAuthToken> GetAuthTokenAsync(string code, string appid = "")
        {
            var config = OpenApi.GetConfig(appid, PlatformType.Mp);
            var url =
                $"https://api.weixin.qq.com/sns/oauth2/access_token?appid={config.AppId}&secret={config.AppSecret}&code={code}&grant_type=authorization_code";
            return await HttpUtil.GetResultAsync<OAuthToken>(url);
        }
#endif
    }
}
